package com.xjtu.duansheli.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class DocumentUtil {
    private static String fileUrl;

    @Value("${ip.address}")
    public void setFileUrl(String address) {
        this.fileUrl = address + "/upload/";
    }

    private static String os = System.getProperty("os.name");

    private static String FilePath;

    static {
        if (os.toLowerCase().startsWith("win")) {
            FilePath = "D:" + File.separator + "temp" + File.separator + "upload" + File.separator;
        } else {
            FilePath = "/root/upload/";
        }
        log.info("文件资源路径:" + FilePath);
    }

    public static Map<String, String> saveDocument(String filename) {

        Map<String, String> temps = new HashMap<String, String>();
        String key = getUniqueKey();
        String path = FilePath + key + filename;
        String url = fileUrl + key + filename;
        log.info("文件存储地址:" + path);
        temps.put("filePath", path);
        temps.put("fileUrl", url);
        return temps;
    }

    /*采用时间+随机数生成唯一ID*/
    public static synchronized String getUniqueKey() {
        int number = (int) ((Math.random() * 9 + 1) * 100);
        return System.currentTimeMillis() + String.valueOf(number);
    }
}
